package com.financing.wap.util;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Header;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

public class MP3Util {
	
	private static Logger logger = Logger.getLogger(MP3Util.class);
	
	public static void main(String[] args) throws IOException, LineUnavailableException, UnsupportedAudioFileException, BitstreamException {
		long current=System.currentTimeMillis();
//		InputStream doRequest = RequstUtil.doRequest("http://stg.superfa.cn/upload/wjtCourse/wjtAudio/20160803/7X5qmL_oTA-niOAbJYcj9XP-6wJURA4I5fY83TTSEyz0nI447kJy7g0-xSRGozS4_1470220584461.mp3");
//		IOUtils.copy(doRequest, new FileOutputStream("D://test1111.mp3"));
//		System.out.println("==="+getAudioPlayTime("D://test - 副本.mp3"));
//		System.out.println("222="+getAudioPlayTime(doRequest));
//		System.out.println("=="+getAmrDuration(new File("D://test2.amr")));
//		System.out.println("==="+convertAmrToMp3("D://test.amr", ""));
		System.out.println(System.currentTimeMillis()-current);
	}
	
	/** 
     * 得到amr的时长 
     *  
     * @param file 
     * @return 
     * @throws IOException 
     */  
    public static long getAmrDuration(File file) throws IOException {  
        long duration = -1;  
        int[] packedSize = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 };  
        RandomAccessFile randomAccessFile = null;  
        try {  
            randomAccessFile = new RandomAccessFile(file, "rw");  
            long length = file.length();//文件的长度  
            int pos = 6;//设置初始位置  
            int frameCount = 0;//初始帧数  
            int packedPos = -1;  
            byte[] datas = new byte[1];//初始数据值  
            while (pos <= length) {  
                randomAccessFile.seek(pos);  
                if (randomAccessFile.read(datas, 0, 1) != 1) {  
                    duration = length > 0 ? ((length - 6) / 650) : 0;  
                    break;  
                }  
                packedPos = (datas[0] >> 3) & 0x0F;  
                pos += packedSize[packedPos] + 1;  
                frameCount++;  
            }  
            duration += frameCount * 20;//帧数*20  
        } finally {  
            if (randomAccessFile != null) {  
                randomAccessFile.close();  
            }  
        }  
        long l = duration/1000;
        return l;  
    }  
	/**
	 * 
	
	* @Title: getAudioPlayTime
	
	* @Description:获取M3时间
	
	* @param @param mp3
	* @param @throws IOException
	* @param @throws BitstreamException    设定文件
	
	* @return void    返回类型
	
	* @throws
	 */
	public static int getAudioPlayTime(String mp3) throws IOException, BitstreamException
	{
		File file = new File(mp3);
		FileInputStream fis=new FileInputStream(file);
		return getAudioPlayTime(fis);
	}
	
	/**
	 * 
	
	* @Title: getAudioPlayTime
	
	* @Description:获取M3时间
	
	* @param @param mp3
	* @param @throws IOException
	* @param @throws BitstreamException    设定文件
	
	* @return void    返回类型
	
	* @throws
	 */
	public static int getAudioPlayTime(FileInputStream fis) throws IOException, BitstreamException
	{
		int b=fis.available();
		Bitstream bt=new Bitstream(fis);
		Header h = bt.readFrame();
		int time = (int) h.total_ms(b);
		int i=time/1000;
		return i;
	}
	public static String convertAmrToMp3(String sourceFilePath, String targetFilePath){
		File source = new File(sourceFilePath);
		if(StringUtil.isNullOrEmptyStr(targetFilePath)){
			targetFilePath = sourceFilePath.replaceAll(".amr", ".mp3");
		}
        File target = new File(targetFilePath);
        
        AudioAttributes audio = new AudioAttributes();  
        Encoder encoder = new Encoder();  
  
        audio.setCodec("libmp3lame");  
        EncodingAttributes attrs = new EncodingAttributes();  
        attrs.setFormat("mp3");  
        attrs.setAudioAttributes(audio); 
        try {
			encoder.encode(source, target, attrs);
		} catch (Exception e) {
			logger.error("mp3Utile convert encode fail", e);
		}
		
		return targetFilePath;
	}
	
}
